/**
 * 
 */
package org.dearsor.elective.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.dearsor.elective.model.Person;
import org.dearsor.elective.model.Student;
import org.dearsor.elective.service.PersonMgr;
import org.dearsor.elective.service.StudentMgr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

/**
 * @author dearshor
 *
 */
@Component
@Results({
	@Result(name = "login-form", location = "loginForm.jsp"),
	@Result(name = "loginFailed", location = "loginFailed.jsp"),
	@Result(name = "welcome",location = "welcome.jsp"),
	@Result(name = "course-list",location = "courseList",type = "redirectAction")
})
public class LoginAction extends ActionSupport implements Preparable {
	
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -8209655280355522937L;
	
	private Person user;
	
	@Autowired
	private PersonMgr personMgr;
	
	@Autowired
	private StudentMgr studentMgr;
	
	@Action("/welcome")
	public String welcome() {
		return "welcome";
	}
	
	@Action("/loginForm")
	public String loginForm() {
		return "login-form";
	}
	
	@Action("/login")
	public String doLogin() {
		setUser(user);
		if (authenticate()) {
			try {
				Student student = studentMgr.find(getUser().getId());
				ActionContext.getContext().getSession().put("currentUser", student);
				return "course-list";
			} catch (DataAccessException e) {
				e.printStackTrace();
				return "loginFailed";
			}
		}
		return "loginFailed";
		
	}
	
	@Action("/logout")
	public String doLogout() {
		if (ActionContext.getContext().getSession().containsKey("currentUser")) {
			ActionContext.getContext().getSession().remove("currentUser");
		}
		return "welcome";
	}
	
	public boolean authenticate() {
		if (getUser() == null || getUser().getName() == null || getUser().getName().length() < 1 || getUser().getPassword() == null || getUser().getPassword().length() < 1) {
			return false;
		}
		try {
			Person person = personMgr.findPersonByUsernameAndPassword(getUser().getName(), getUser().getPassword());
			setUser(person);
			return true;
		} catch (DataAccessException e) {
			e.printStackTrace();
			return false;
		}
	}

	public void prepare() throws Exception {
		setUser(new Student());
	}

	public void setUser(Person user) {
		this.user = user;
	}

	public Person getUser() {
		return user;
	}

}
